package com.hw.backapi.aop;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hw.backapi.event.LogEvent;
import com.hw.backapi.service.IAdminLogService;
import com.hw.common.annotation.MyLogAdmin;
import com.hw.common.utils.ApplicationContextUtil;
import com.hw.common.utils.log.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @author lipeng
 * @description 日志记录
 * @date 2023/3/7 9:56
 */
@Component
@Aspect
@Slf4j
@Order(0)
public class LogAopConfig {

    @Autowired
    IAdminLogService adminLogServiceImpl;

    @Pointcut("execution(* com.hw.backapi.controller.*.*(..))")
    public void pointcut(){}

    @Before("pointcut() && @annotation(logAdmin)")
    public void before(JoinPoint joinpoint, MyLogAdmin logAdmin){
        LogUtil.writeRequestLog(joinpoint);

        if(StrUtil.isNotEmpty(logAdmin.label())) {
            ApplicationContextUtil.getApplicationContext().publishEvent(
                    new LogEvent(adminLogServiceImpl.getPublishLog(logAdmin.label(), JSONUtil.toJsonStr(joinpoint.getArgs())))
            );
        }
    }
}
